# ~*~ coding: utf-8 ~*~
from flask import request, views, render_template, jsonify
from flask_login import current_user

from apps.common.utils import fill_date_to_timestamp, timestamp_obj_to_str
from apps.common.mixin import CompatibleWithSelect2Mixin
from apps.common import response
from apps.extensions import db
from apps.perms.mixin import PermissionRequiredMixin, LoginRequiredMixin
from ...models import IntervalSchedule, PeriodicTask
from ...forms import IntervalForm
from ...utils import create_or_update_periodic_task


__all__ = [
    'IntervalListAPI', 'IntervalListView', 'IntervalCreateView',
    'IntervalUpdateView', 'IntervalDeleteView',
]


class IntervalListAPI(CompatibleWithSelect2Mixin, PermissionRequiredMixin, LoginRequiredMixin, views.MethodView):
    permission_required = 'tasks-interval-list'

    def get(self):
        create_time = request.args.get('create_time')
        start_time = end_time = None
        if create_time:
            start_time = fill_date_to_timestamp('start', create_time.split('~')[0])
            end_time = fill_date_to_timestamp('end', create_time.split('~')[1])

        filter_conditions = {
            'and': [
                ('create_time', 'gte', start_time),
                ('create_time', 'lte', end_time),
            ],
            'or': [
                # ('name', 'like', request.args.get('search')),
            ],
        }

        # 排序
        sort = request.args.get('sort') or 'create_time'
        order = request.args.get('order') or 'desc'
        order_by_list = [(sort, order), ]

        # 分页
        offset = request.args.get('offset') or 0
        limit = request.args.get('limit') or 12

        # Compatible with select2
        if request.values.get('type') == 'select2':
            filter_conditions, order_by_list, offset, limit = self.select2_queryset()

        intervals, count = IntervalSchedule.get_queryset(filter_conditions=filter_conditions,
                                                         order_by_list=order_by_list,
                                                         offset=offset, limit=limit)
        results = list()
        for interval in intervals:
            results.append({
                'id': interval.id,
                'every': interval.every,
                'period': interval.period,
                'create_by': interval.create_by,
                'create_time': timestamp_obj_to_str(interval.create_time),
                'text': interval.__str__()
            })

        resp = {
            "data": {
                "rows": results,
                "total": count
            }
        }
        return jsonify(resp)


class IntervalListView(PermissionRequiredMixin, LoginRequiredMixin, views.MethodView):
    permission_required = 'tasks-interval-list'

    def get(self):
        return render_template('tasks/periodic/interval_list.html')


class IntervalUpdateView(PermissionRequiredMixin, LoginRequiredMixin, views.MethodView):
    permission_required = 'tasks-interval-update'

    def get(self, pk):
        instance = db.session.query(IntervalSchedule).get(pk)
        content = {
            'id': instance.id,
            'every': instance.every,
            'period': instance.period,
        }
        return render_template('tasks/periodic/interval_update.html', **content)

    def post(self, pk):
        form = IntervalForm(request.values)
        instance = db.session.query(IntervalSchedule).get(pk)
        if form.validate():
            _clean_data = form.data
            # if instance.name != _clean_data.get('name'):
            #     if db.session.query(Interval).filter_by(name=_clean_data.get('name')).count():
            #         return response.params_error({
            #             'field': 'name',
            #             'message': '环境平台名称不能重复'
            #         })

            instance.every = _clean_data.get('every')
            instance.period = _clean_data.get('period')
            instance.create_by = current_user.name
            instance.update()

            # 更新所有关联的定时任务
            periodic_list = db.session.query(PeriodicTask).filter(PeriodicTask.interval_id == instance.id).all()
            for periodic in periodic_list:
                create_or_update_periodic_task(periodic, interval=instance)
            return response.success()
        else:
            return response.params_error(form.get_error())


class IntervalCreateView(PermissionRequiredMixin, LoginRequiredMixin, views.MethodView):
    permission_required = 'tasks-interval-create'

    def get(self):
        return render_template('tasks/periodic/interval_create.html')

    def post(self):
        form = IntervalForm(request.values)
        if form.validate():
            _clean_data = form.data
            # if db.session.query(IntervalSchedule).filter_by(name=_clean_data.get('name')).count():
            #     return response.params_error({
            #         'field': 'name',
            #         'message': '环境平台名称不能重复'
            #     })

            interval = IntervalSchedule()
            interval.every = _clean_data.get('every')
            interval.period = _clean_data.get('period')
            interval.create_by = current_user.name
            db.session.add(interval)
            db.session.commit()
            return response.success()
        else:
            return response.params_error(form.get_error())


class IntervalDeleteView(PermissionRequiredMixin, LoginRequiredMixin, views.MethodView):
    permission_required = 'tasks-interval-delete'

    def post(self, pk):
        instance = db.session.query(IntervalSchedule).get(pk)
        if db.session.query(PeriodicTask).filter(PeriodicTask.interval_id == instance.id).count():
            return response.params_error(data={
                'message': '该间隔调度有定时任务关联，不直接删除'
            })
        instance.delete()
        return response.success()

